package com.boot.unity.api.common;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES {

    private static final String CHARSET = "utf-8";
    private static final String KEY_ALGORITHM = "AES";
    private static final String CHAR_SET = "UTF-8";

    public AES() {
    }

    public static String encrypt(String plaintext, String key) {
        return encrypt(plaintext, key, (String)null);
    }

    public static String decrypt(String cipherText, String key) {
        return decrypt(cipherText, key, (String)null);
    }

    public static String encrypt(String plaintext, String key, String encryptModel) {
        if (encryptModel == null) {
            encryptModel = "ECB";
        }

        try {
            key = getMD5(key);
            byte[] raw = new byte[0];
            if (key != null) {
                raw = key.getBytes("UTF-8");
                SecretKeySpec sKeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES/" + encryptModel + "/PKCS5Padding");
                if ("ECB".equals(encryptModel)) {
                    cipher.init(1, sKeySpec);
                } else {
                    IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
                    cipher.init(1, sKeySpec, iv);
                }

                byte[] encrypted = cipher.doFinal(plaintext.getBytes("UTF-8"));
                String encodeResult = (new BASE64Encoder()).encode(encrypted);
                encodeResult = encodeResult.replaceAll(System.getProperty("line.separator"), "");
                return encodeResult;
            } else {
                return null;
            }
        } catch (Exception var8) {
            var8.printStackTrace();
            return null;
        }
    }

    public static String decrypt(String cipherText, String key, String encryptModel) {
        if (encryptModel == null) {
            encryptModel = "ECB";
        }

        try {
            key = getMD5(key);
            byte[] raw = new byte[0];
            if (key != null) {
                raw = key.getBytes("UTF-8");
                SecretKeySpec sKeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES/" + encryptModel + "/PKCS5Padding");
                if ("ECB".equals(encryptModel)) {
                    cipher.init(2, sKeySpec);
                } else {
                    IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
                    cipher.init(2, sKeySpec, iv);
                }

                byte[] bytes = (new BASE64Decoder()).decodeBuffer(cipherText);

                try {
                    byte[] original = cipher.doFinal(bytes);
                    return new String(original, "UTF-8");
                } catch (Exception var8) {
                    var8.printStackTrace();
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception var9) {
            var9.printStackTrace();
            return null;
        }
    }

    private static String getMD5(String str) {
        if (str == null) {
            return null;
        } else {
            char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

            try {
                byte[] btInput = str.getBytes();
                MessageDigest mdInst = MessageDigest.getInstance("MD5");
                mdInst.update(btInput);
                byte[] md = mdInst.digest();
                int length = md.length;
                char[] strByteArr = new char[length * 2];
                int k = 0;
                byte[] var8 = md;
                int var9 = md.length;

                for(int var10 = 0; var10 < var9; ++var10) {
                    byte b = var8[var10];
                    strByteArr[k++] = hexDigits[b >>> 4 & 15];
                    strByteArr[k++] = hexDigits[b & 15];
                }

                return (new String(strByteArr)).substring(8, 24);
            } catch (Exception var12) {
                var12.printStackTrace();
                return null;
            }
        }
    }

    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }


    /**
     * hex字符串转byte数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    private static SecretKeySpec getAESKey(String encKey) throws Exception {
        SecretKeySpec key = null;

        byte[] encKeyByte = encKey.getBytes("UTF-8");

        byte[] keyByte = new byte[16];// 创建一个空的16位字节数组,默认值为0
        for (int i = 0; i < encKeyByte.length && i < keyByte.length; i++) {
            // 取传入字符串的前16位字节码为密钥字节数组，不足16位的，则采用默认值0
            keyByte[i] = encKeyByte[i];
        }
        key = new SecretKeySpec(keyByte, "AES");// 创建一个AES加密密钥
        return key;
    }

    public static void main(String[] args) {


        String text="";
        text   ="{\n" +
                "    \"code\": \"10000\",\n" +
                "    \"data\": {\"total\":1,\"rows\":[{\"bdate\":\"20190130\",\"ratemny\":41323.04,\"loanmnhs\":180,\"loanbal\":287939.25,\"loancode\":\"810300801481000017\",\"loanrate\":5.73,\"agrcode\":\"BC2019013000000021\",\"housearea\":111.93,\"mntpay\":2656.68,\"payday\":\"21\",\"loanstate\":\"1\",\"loanmny\":320000,\"fpaymny\":485734,\"housemny\":805734,\"address\":\"齐鲁师范园小区10号楼1单元2001号\",\"pername\":\"王静\",\"basemny\":32060.75,\"edate\":\"20340130\",\"repayway\":\"01\",\"cardcode_2\":\"370122197205162740\",\"codetype\":\"A\"}]},\n" +
                "    \"message\": \"成功\"\n" +
                "}";
        String aesKey = "SECRET20210706KM7F2A11";//密钥
        String encrypt = encrypt(text, aesKey);//加密
        System.out.println(encrypt);
        System.out.println(decrypt(encrypt,aesKey));//解密
        //{"ciphertext":"uZ6c/zT9hhncU5ixPvGXZYnBkv/6kCbKPgsByzhffMYGSO1iXcghFJWz15FG0XBdr7dxQsDn/h7/NqiUE1kbLp3mtdsNzbQPUHy5jpZYvTx0GsQqSEBxITYkXKOSHDg7mvcVYvraf1VVZZK3NCZUcoSWmdP9wRF5I/eIOKPEp3NbFHqlOLnA8+fCrIwKmUHY","key":"SECRET2024062580htlhd7"}
        String encryptCode = "uZ6c/zT9hhncU5ixPvGXZYnBkv/6kCbKPgsByzhffMYGSO1iXcghFJWz15FG0XBdr7dxQsDn/h7/NqiUE1kbLp3mtdsNzbQPUHy5jpZYvTx0GsQqSEBxITYkXKOSHDg7mvcVYvraf1VVZZK3NCZUcoSWmdP9wRF5I/eIOKPEp3NbFHqlOLnA8+fCrIwKmUHY";
        System.out.println(decrypt(encryptCode,"SECRET2024062580htlhd7"));


//        encryptCode = "6pweX/u9coliQEIIop80CgadDwhMXQPX9Je2TR3m5YhmAnAQugeBhP+ZrAiiF9GC0VqAxOFwB1zdkj2AwdP0rWoX4Qj+7SlelQNIzDK5iCIFwoeR3BNGPzFtsXaGTEFNLqwmrNx0K0eXyhPCc2wJFyR8xw9Vn91psEoQFQs7kZAlFk7r/S2vnCUFwWpl8bNl";
//        System.out.println(decrypt(encryptCode,"SECRET20240625vxrjmzif"));
//
//
//        encryptCode = "dZCo591INTOlfBtYFkBw2NbveBsb5MLllQtsNCC80RCuGDjwQCRfAjE13S9nIBO5";
//        System.out.println(decrypt(encryptCode,"SECRET2024062580htlhd7"));


        // text = "{\"string3\":\"\",\"string1\":\"\",\"string2\":\"\",\"pageSize\":10,\"currentPage\":1,\"agrcode\":\"911C0000424618\",\"day_id\":\"20240101'and'20240131\"}";
        text="{\"string3\":\"\",\"string1\":\"\",\"string2\":\"\",\"pageSize\":100,\"currentPage\":1,\"agrcode\":\"911C0000427036\",\"day_id\":\"20210401'and'20240729\"}";
        aesKey = "SECRET2024062580htlhd7";//密钥1
        encrypt = encrypt(text, aesKey);//加密
        System.out.println(encrypt);


        text="{\"cardcode_2\":\"371102198310183850\",\"string3\":\"\",\"pername\":\"宋玉龙\",\"codetype\":\"01\",\"string1\":\"\",\"string2\":\"\",\"pageSize\":100,\"currentPage\":1}";
        aesKey = "SECRET2024062580htlhd7";//密钥1
        encrypt = encrypt(text, aesKey);//加密
        System.out.println(encrypt);







    }


}
